import { LocalizationService } from '@abp/localization/localization.service';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

import {LogService} from '@abp/log/log.service';
import {TokenService} from '@abp/auth/token.service';
import {LoginVM, ServiceProxy, BaseDTO} from '@shared/service-proxy/service-proxies';
import { NzMessageService } from 'ng-zorro-antd';
import { AppConsts } from '@shared/AppConsts';

@Injectable({
  providedIn: 'root'
})

export class LoginService {
  localizationSourceName = AppConsts.localization.defaultLocalizationSourceName;
  constructor(
    private _router: Router,
    private _tokenAuthService: ServiceProxy,
    private _tokenService: TokenService,
    private localization:LocalizationService,
    private _logService: LogService,
    private message: NzMessageService
  ) {
  }

  authenticate(model: LoginVM): void {

    this._tokenAuthService.loginUsingPOST(model).subscribe((result: BaseDTO) => {
      this.login(result);
    });
  }

  private login(authenticateResult: BaseDTO) {

    if (authenticateResult.result != null) {
      const accessToken = authenticateResult.result.tokenId;
      // const accessToken = authenticateResult.expireInSeconds;
      this._tokenService.setToken(
        accessToken,
        undefined
      );
      location.href = '/';
    } else {
      this.message.error(this.l(authenticateResult.error.message));
    }
  }

  l(key: string, ...args: any[]): string {
    return this.ls(this.localizationSourceName, key, args);
  }

  ls(sourcename: string, key: string, ...args: any[]): string {
    let localizedText = this.localization.localize(key, sourcename);

    if (!localizedText) {
      localizedText = key;
    }

    if (!args || !args.length) {
      return localizedText;
    }

    args[0].unshift(localizedText);

    return abp.utils.formatString.apply(this, args[0]);
  }
}
